﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Fly.Common.Linq;
using Newtonsoft.Json;
using Telerik.Web.UI;
using System.Configuration;


namespace RN.ERP.Web.Person
{
    public partial class PersonEmpList14 : BasePage
    {
        #region  公共属性
        /// <summary>
        /// 登陆用户guid
        /// </summary>
        protected string CorpUserGuid
        {
            get 
            {
                return UserInfo.CorpUserGuid;
            }
        }
        /// <summary>
        /// 当前市场
        /// </summary>
        protected string AreaCode
        {
            get
            {
                return UserInfo.CurrentArea;
            }
        }
        /// <summary>
        /// 登陆用户类型
        /// </summary>
        protected string RoleType
        {
            get
            {
                return UserInfo.RoleType;
            }
        }
        /// <summary>
        /// 登录用户roleid
        /// </summary>
        protected string RoleId
        {
            get
            {
                return UserInfo.RoleId;
            }
        }
        /// <summary>
        /// 作为查询地区限定条件
        /// </summary>
        protected string AreaCodeWhere
        {
            get
            {
                return UserInfo.AreaCode;
            }
        }
        /// <summary>
        /// 标识在管理端通过企业guid查询列表
        /// </summary>
        protected string tag
        {
            get 
            {
               return ViewState["tag"].ToString();
            }
        }
        /// <summary>
        /// 人员类型
        /// </summary>
        private int classId;
        /// <summary>
        /// 人员分组
        /// </summary>
        protected string GroupID
        {
            get
            {
                string groupid = string.Empty;
                if (Request.QueryString["groupId"] != null)
                {
                    return Request.QueryString["groupId"].Trim();
                }
                return groupid;
            }
        }

        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Initial();
            }
        }
        #region 页面设置
        /// <summary>
        /// 参数及设置按钮显示
        /// </summary>
        private void Initial()
        {
            int opt = 0;//默认是一级页面
            string areaCode = string.Empty;
            string flowCode = string.Empty;
            int groupId = 0;
            ////人员类型
            if (Request.QueryString["classId"] != null)
            {
                int.TryParse(Request.QueryString["classId"].Trim(),out classId);
            }
            hdClassId.Value = classId.ToString();
            ////人员类型分组
            if (Request.QueryString["groupId"] != null)
            {
                int.TryParse(Request.QueryString["groupId"].Trim(), out groupId);
                hdGroupId.Value = groupId.ToString();
            }
            if (Request.QueryString["ispost"] != null)
            {
                hdIsPost.Value = Request.QueryString["ispost"].Trim();
            }

            //表示是否从统计页面来
            if (Request.QueryString["opt"] != null)
            {
                int.TryParse(Request.QueryString["opt"].Trim(), out opt);
            }
            //统计页面参数-地区号
            if (Request.QueryString["areacode"] != null)
            {
                areaCode = Request.QueryString["areacode"].Trim();
            }
            //统计页面参数-审核状态
            if (Request.QueryString["flowcode"] != null)
            {
                flowCode = Server.UrlDecode(Request.QueryString["flowcode"].Trim());
            }
            ////证书类型
            if (Request.QueryString["itemType"] != null)
            {
                FormatQueryParam(Request.QueryString["itemType"].Trim());
            }
            ViewState["opt"] = opt;
            ViewState["areaCode"] = areaCode;
            ViewState["flowCode"] = flowCode;
            ViewState["tag"] = 0;
            ///用户端登陆
            SetUsersShow();
            //企业Guid
            if (!string.IsNullOrEmpty(Request.QueryString["corpUserGuid"]))
            {
                ViewState["tag"] = 1;//标识在通过企业guid查询列表
                hdCorpUserGuid.Value = Request.QueryString["corpUserGuid"].Trim();
            }
            if (hdIsPost.Value.Equals("1"))
            {
                btnImport.Style["display"] = "none";
                rgPersonList.Columns.FindByDataField("StrTitleDetails").Visible = false;
            }
            else
            {
                rgPersonList.Columns.FindByDataField("Post_Title").Visible = false;
            }
          
        }
        /// <summary>
        /// 根据用户页配置面内容
        /// </summary>
        private void SetUsersShow()
        {
            if (RoleType == "User")
            {
                UserDiv.Visible = true;//企业端操作按钮div
                ///用户端登陆
                hdCorpUserGuid.Value = CorpUserGuid;
                return;
            }
            //企业端不显示的查询条件
            BindFlowCode();
            ManagerDiv.Visible = true;//管理端操作按钮
            lblCorpName.Visible = true;
            txtCorpName.Visible = true;
            dropEmpStatus.Visible = true;
            lblEmpFlow.Visible = true;
            if (ViewState["opt"].ToString() == "0" && dropEmpStatus.Items.Count >= 1)
            {
                dropEmpStatus.SelectedIndex = 1;
            }
        }
        /// <summary>
        /// 取得证书类型参数--参数格式：x,x或1;x,x
        /// </summary>
        /// <param name="itemType"></param>
        private void FormatQueryParam(string itemType)
        {
            if (itemType.Contains(";"))
            {
                hdEmpItemFlag.Value = itemType.Split(';')[0];
                hdEmpItemType.Value = itemType.Split(';')[1];
            }
            else
            {
                hdEmpItemType.Value = itemType;
            }
         
        }
        /// <summary>
        /// 加载审核状态下拉列表
        /// </summary>
        private void BindFlowCode()
        {
            string classId = hdClassId.Value;
            if (string.IsNullOrEmpty(classId) || classId == "0")
            {
                classId = "2511";
            }
            var dic = UtilitiesTool.GetAllFlowStatus(classId, AreaCode, RoleId);
            dropEmpStatus.DataSource = dic;
            dropEmpStatus.DataTextField = "key";
            dropEmpStatus.DataValueField = "value";
            dropEmpStatus.DataBind();
        }

        #endregion

        #region 取得数据源
        /// <summary>
        /// 取得人员信息参数列表
        /// </summary>
        /// <returns></returns>
        private string GetQueryConditions()
        {
            //高级查询返回条件
            if (!string.IsNullOrEmpty(hdSearchEndStr.Value))
            {
                return Server.HtmlDecode(hdSearchEndStr.Value);
            }
            //审核状态
            string flowCodes = dropEmpStatus.SelectedValue;
            //作为统计页面二级页
            if (ViewState["opt"].ToString() == "1")
            {
                flowCodes = ViewState["flowCode"].ToString();
            }
            //管理端
            if (RoleType == "Manager")
            {
                if (flowCodes == "")
                {
                    flowCodes = "019";                  
                }
            }
            else
            {
                flowCodes = string.Empty;
            }
            //人员类型分组
            int groupId = 0;
            if (hdGroupId.Value != "0")
            {
                int.TryParse(hdGroupId.Value.Trim(), out groupId);
            }
            List<ModelService.QueryPersonInfoConditionNew> query = new List<ModelService.QueryPersonInfoConditionNew>();
            ////人员类型分组条件
            ////ModelService.QueryPersonInfoConditionNew queryCondition = GetQueryCondition(flowCodes, groupId,0);
            ////query.Add(queryCondition);
            ////证书类型分组条件
            if (groupId > 0 && !hdIsPost.Value.Equals("1"))
            {
                ModelService.QueryPersonInfoConditionNew queryCondition1 = GetQueryCondition(flowCodes, groupId, 1);
                query.Add(queryCondition1);
            }
            if (hdIsPost.Value.Equals("1"))
            {
                ModelService.QueryPersonInfoConditionNew queryCondition1 = GetQueryCondition(flowCodes, groupId, 0);
                query.Add(queryCondition1);
            }
            return  JsonConvert.SerializeObject(query);
        }
        /// <summary>
        /// 取得人员参数项
        /// </summary>
        /// <param name="flowCode"></param>
        /// <returns></returns>
        private ModelService.QueryPersonInfoConditionNew GetQueryCondition(string flowCode, int groupId, int flag)
        {
            ///设置查询参数
            ModelService.QueryPersonInfoConditionNew queryCondition = new ModelService.QueryPersonInfoConditionNew();
            //queryCondition.TypeFlag = new ParameterValue<string> { V = "-1", O = OptEnum.Like };
            int.TryParse(hdClassId.Value,out classId);
            //人员类型
            if (classId > 0)
            {
                queryCondition.ClassId = new ParameterValue<int?> { V = classId, O = OptEnum.Equal };
            }
            //人员类型分组
            if (groupId > 0 && !hdIsPost.Value.Equals("1"))
            {
                if (flag == 0)
                {
                    queryCondition.GroupID = new ParameterValue<int?> { V = groupId, O = OptEnum.Equal };
                }
                else
                {
                    queryCondition.GroupTreeID = new ParameterValue<int?> { V = groupId, O = OptEnum.Equal };
                }
            }
            //审核状态
            if (!string.IsNullOrEmpty(flowCode))
            {
                var flowCodes = new List<ParameterValue<string>>();
                if (flowCode == "019")
                {
                    //管理端全部不包含未上报
                    flowCodes.Add(new ParameterValue<string> { V = flowCode, O = OptEnum.Like });  
                }
                else
                {
                    string[] arry = flowCode.Split('|');
                    foreach (string flow in arry)
                    {
                        var code = new ParameterValue<string> { V = flow, O = OptEnum.Equal };
                        flowCodes.Add(code);
                    } 
                }
                queryCondition.FlowCode = new ParameterValues<string>
                {
                    Logic = LogicEnum.Or,
                    Values = flowCodes
                };
            }
            //企业名称
            if (!string.IsNullOrEmpty(txtCorpName.Text.Trim()))
            {
                queryCondition.corpName = new ParameterValue<string> { V = txtCorpName.Text.Trim(), O = OptEnum.Like };
            }
            //人员名称
            if (!string.IsNullOrEmpty(txtEmpName.Text.Trim()))
            {
                queryCondition.Name = new ParameterValue<string> { V=txtEmpName.Text.Trim(),O=OptEnum.Like};
            }
            ///身份证
            if (!string.IsNullOrEmpty(txtEmpIdCard.Text.Trim()))
            {
                queryCondition.IDCard = new ParameterValue<string> { V = txtEmpIdCard.Text.Trim(), O = OptEnum.Equal }; 
            }
            //统计传递地区
            if (!string.IsNullOrEmpty(ViewState["areaCode"].ToString()))
            {
                if (ViewState["areaCode"].ToString().IndexOf("00") > 1)//本地
                {
                    queryCondition.AreaCode = new ParameterValue<string> { V = ViewState["areaCode"].ToString().Replace("00", "").Trim(), O = OptEnum.StartWith };
                }
                else if (ViewState["areaCode"].ToString().IndexOf("99") > 1)//外地
                {
                    queryCondition.AreaCode = new ParameterValue<string> { V = ViewState["areaCode"].ToString().Replace("99", "").Trim(), O = OptEnum.NotStartWith };
                }
                else if (ViewState["areaCode"].ToString().Trim().Length > 2)//查询子地区
                {
                    queryCondition.AreaCode = new ParameterValue<string> { V = ViewState["areaCode"].ToString(), O = OptEnum.StartWith };
                }
            }
            else
            {
                /////子地区查询
                if (RoleType == "Manager" && tag == "0")
                {
                    if (AreaCodeWhere.Length>2)//本地
                    {
                        queryCondition.AreaCode = new ParameterValue<string> { V = AreaCodeWhere, O = OptEnum.StartWith };
                    }
                }
            }
            //证书类型包含多种类型的人员（hdEmpItemFlag=1标识不包含）
            if (!string.IsNullOrEmpty(hdEmpItemType.Value.Trim()) && hdEmpItemFlag.Value!="1")
            {
                int code = 0;
                var list = new List<ParameterValue<int>>();
                var arrt = hdEmpItemType.Value.Trim().Split(',');
                foreach (var a in arrt)
                {
                    if (int.TryParse(a.Trim(),out code))
                    {
                       var area= new ParameterValue<int>(){ O=OptEnum.Equal,V=code};
                       list.Add(area);
                    }
                }
                queryCondition.TypeFlags = new ParameterValues<int>()
                {
                    Logic = LogicEnum.Or,
                    Values = list
                };
            }
            //企业guid
            if (!string.IsNullOrEmpty(hdCorpUserGuid.Value.Trim()))
            {
                Guid userGuid = Guid.Empty;
                Guid.TryParse(hdCorpUserGuid.Value.Trim(), out userGuid);
                queryCondition.CorpGuid = new ParameterValue<Guid> { V = userGuid, O = OptEnum.Equal };
            }
            return queryCondition;
        }
        /// <summary>
        /// 其他人员，取得被排除的人员类型信息
        /// </summary>
        /// <param name="empGuid"></param>
        /// <param name="areaCode"></param>
        private List<int> GetEmpCertList()
        {
            List<int> certList = new List<int>();
             if (hdEmpItemFlag.Value == "1" && !string.IsNullOrEmpty(hdEmpItemType.Value.Trim()))
             {
                 int temp = 0;
                 string[] list = hdEmpItemType.Value.Trim().Split(',');
                 foreach (string a in list)
                 {
                     if (int.TryParse(a, out temp))
                     {
                         certList.Add(temp);
                     }
                 }
             }
             return certList;
        }
        /// <summary>
        /// 绑定人员数据列表
        /// </summary>
        private void rgPersonDataBind()
        {
            int currentPageIndex = rgPersonList.CurrentPageIndex;
            int pageSize = rgPersonList.MasterTableView.PageSize;
            string result = string.Empty;
            if (hdIsPost.Value != "1")
            //try
            {
                using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
                {
                    string queryStr = GetQueryConditions();
                    List<int> certList = GetEmpCertList();
                    string certs = string.Empty;
                    if (certList.Count > 0)
                    {
                        certs = JsonConvert.SerializeObject(certList);
                    }
                    rgPersonList.VirtualItemCount = client.GetEmpManagerByCertCount(queryStr, certs, AreaCode);
                    result = client.GetEmpManagerByCertList(currentPageIndex + 1, pageSize, queryStr, certs, AreaCode);
                    rgPersonList.DataSource = JsonConvert.DeserializeObject<List<ModelService.tb_Emp_Manager>>(result);
                }
            }
            else
            {
                ////职称人员
                using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
                {
                    string queryStr = GetQueryConditions();
                    string certs = string.Empty;
                    int count = 0;
                    
                    result = client.GetEmpManagerPostList(currentPageIndex + 1, pageSize, queryStr, certs, AreaCode, out count);
                    rgPersonList.VirtualItemCount = count;
                    rgPersonList.DataSource = JsonConvert.DeserializeObject<List<ModelService.tb_Emp_Manager>>(result);
                }
            }
            //catch
            //{ }
        }
        /// <summary>
        /// 绑定查询列表
        /// </summary>
        private void PersonDataBind()
        {
            //将高级查询和统计查询条件置空
            hdSearchEndStr.Value = "";
            ViewState["opt"] = 0;
            ViewState["areaCode"] = "";
            ViewState["flowCode"] = "";
            rgPersonList.CurrentPageIndex = 0;
            rgPersonDataBind();
            rgPersonList.DataBind();
        }
        #endregion

        #region 事件处理

        /// <summary>
        /// 绑定人员信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void rgPersonList_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            rgPersonDataBind();
        }
        /// <summary>
        /// 审核状态查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //protected void dropEmpStatus_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    PersonDataBind();
        //}
        /// <summary>
        /// 修改人员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdatePerson_Click(object sender, EventArgs e)
        {
            string classID = string.Empty;
            string empGuid = GetSelCheck();
            if (string.IsNullOrEmpty(empGuid))
            {
                RadWindowManager1.RadAlert("请选择要操作的项！", 300, 150, "提示", "");
            }
            if (empGuid.IndexOf(",") > 0)
            {
                RadWindowManager1.RadAlert("只能选择一个修改项！", 300, 150, "提示", "");
            }
            string url = string.Format("PersonEmpInfo.aspx?type=14&empGuid={0}&typeFlag={1}&groupId={2}&ispost={3}&classId={4}", empGuid, "-1", hdGroupId.Value, hdIsPost.Value, classID);

            Response.Redirect(url, true);
        }
        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbtnEmpSreach_Click(object sender, EventArgs e)
        {
            PersonDataBind();
        }
        /// <summary>
        /// 取得客户端选择的项
        /// </summary>
        /// <returns></returns>
        private string GetSelCheck()
        {
            string empGuid = string.Empty;
            foreach (GridDataItem item in rgPersonList.Items)
            {
                System.Web.UI.HtmlControls.HtmlInputCheckBox box = (System.Web.UI.HtmlControls.HtmlInputCheckBox)item.FindControl("ckb");
                if (box.Checked)
                {
                    empGuid = box.Value.Trim().Split(',')[0] + ",";
                }
            }
            if (empGuid.Length > 1)
            {
                empGuid = empGuid.TrimEnd(',');
            }
            return empGuid;
        }

        /// <summary>
        /// 输出JSON格式数据到页面
        /// </summary>
        /// <param name="dataStr"></param>
        private void OutputData(string dataStr)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(dataStr);
            HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 客户端grid刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            if (e.Argument == "Rebind")
            {
                rgPersonList.MasterTableView.SortExpressions.Clear();
                rgPersonList.MasterTableView.GroupByExpressions.Clear();
                rgPersonList.Rebind();
            }
           
        } 

        #endregion

        protected void rgPersonList_ItemDataBound(object sender, GridItemEventArgs e)
        {
           
        }
    }
}
